package com.garbagecode.resultbounds;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Plugin;

import com.garbagecode.resultbounds.dialect.Dialect;
import com.garbagecode.resultbounds.dialect.MySqlDialect;

public abstract class AbstractPaginationInterceptor implements Interceptor {
  private static Dialect dialect = new MySqlDialect();
  private static List<ResultMap> resultMaps;
  public static final String PROPERTY_DIALECT_NAME = "dialect";
  
  //
  // 初始属性 resultMaps
  //
  static {
    String id = AbstractPaginationInterceptor.class.getName() + "." + Long.class.getName();
    Class<?> type = Long.class;
    ArrayList<ResultMapping> resultMappings = new ArrayList<ResultMapping>();

    ResultMap.Builder resultMapBuilder = new ResultMap.Builder(null, id, type, resultMappings);
    ResultMap newResultMap = resultMapBuilder.build();

    resultMaps = new ArrayList<ResultMap>();
    resultMaps.add(newResultMap);
    resultMaps = Collections.unmodifiableList(resultMaps);
  }

  @Override
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  @Override
  public void setProperties(Properties properties) {
    String dialectName = properties.getProperty(PROPERTY_DIALECT_NAME);
    
    //
    // 初始属性 dialect
    //
    if (dialectName != null) {
      try {
        dialect = (Dialect) Class.forName(dialectName.trim()).newInstance();
      } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new RuntimeException(e);
      }
    }
  }

  protected static Dialect getDialect() {
    return dialect;
  }

  protected static List<ResultMap> getResultMaps() {
    return resultMaps;
  }

}
